import {Injectable} from '@angular/core';
import {CanActivate, ActivatedRouteSnapshot, RouterStateSnapshot, Router} from '@angular/router';
import {Observable} from 'rxjs';
import {TokenService} from './token.service';
import {environment} from '../../environments/environment';

@Injectable({
  providedIn: 'root'
})
export class AuthGuard implements CanActivate {


  constructor(
    private service: TokenService,
    private router: Router
  ) {
  }

  canActivate(
    next: ActivatedRouteSnapshot,
    state: RouterStateSnapshot): Observable<boolean> | Promise<boolean> | boolean {
    if (state.url.startsWith('/login?code=')) {
      const code = state.url.split('code=')[1];
      this.service.getToken(code);
      this.router.navigate(['/']);
      return false;
    }
    if (this.service.noAuth()) {
      window.location.href = environment.oauth + '/oauth/authorize?response_type=code&client_id=client' +
        '&redirect_uri=http%3A%2F%2Flocalhost%3A4200%2Flogin';
      return false;
    }
    return true;
  }
}
